﻿<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<%@ Import Namespace="EzDesk.Utility.Json" %>
<asp:Content ID="Content2" ContentPlaceHolderID="PageTitle" runat="server">
    <title>项目计划</title>
    </asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="PageStyles" runat="server">
    <link href="../../Content/project/project.css" rel="stylesheet" type="text/css" />
    <link href="../../Content/project/project.workitemlist.css" rel="stylesheet" type="text/css" />
    <link href="../../Content/ui.button.css" rel="stylesheet" type="text/css" />
    <link href="../../Content/table_jui.css" rel="stylesheet" type="text/css" />
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="PageScripts" runat="server">
    <script src="../../Scripts/Project/projectTab.js" type="text/javascript"></script>
    <script type="text/javascript">
        var Global = {
            projectId: null,
            project: null
        };

        $(function () {
            Global.projectId = '<%= Model.ProjectId %>';
            Global.project = EzDesk.Service.GetFullProjectById_Sync(undefined, { id: Global.projectId });

            $('#tabs').projectTab(Global.projectId, 'link-tasks');

            if (ProjectInfo) {
                ProjectInfo.ShowProject(Global.project);
            }
        });
    </script>
    <link href="../../Scripts/Project/dhtmlxgantt.css" rel="stylesheet" type="text/css" />
    <script src="../../Scripts/Project/dhtmlxcommon.js" type="text/javascript"></script>
    <script src="../../Scripts/Project/dhtmlxgantt.js" type="text/javascript"></script>
    <script src="../../Scripts/Project/dhtmlxgantt.ext.js" type="text/javascript"></script>
    <script src="../../Scripts/Project/TestData.js" type="text/javascript"></script>
    <textarea id="taskTemplate" style="display: none">
        <div id="{$T.Id}">
            <ul class="fieldslist">
            <li class="l">名称:</li>
            <li class="r"><input type="text" class="txt-name" value="{$T.Name}"/></li>
            <li class="l">负责人:</li>
            <li class="r"><select class="select-director"></select></li>
            <li class="l" style="display:none;" class="lbl-template">模板:</li>
            <li class="r" style="display:none;" class="lbl-template"><select class="select-template"></select></li>

            <li class="l" >开始时间:</li>
            <li class="r" ><input type="text" class="txt-est" value="{$T.EST}"/></li>
            <li class="l" style="display:none;">工作量:</li>
            <li class="r" style="display:none;"><input type="text" class="txt-duration" value="{$T.Duration}"/>小时</li>
            <li class="l" style="display:none;">前置任务:</li>
            <li class="r" style="display:none;"><select class="select-pretask" /></li>
            <li class="l"></li>
            <li class="r"><button class="btn-submit">添加</button></li>
            </ul>
        </div>
    </textarea>
    <script>
        var ganttChartControl;
        var currentTaskInfo;
        $(function () {
            GanttLoad(Global.project);
            $('#btn-add-workitem').click(doCreateWorkitem);
        });

        function GanttLoad(project) {
            ganttChartControl = new GanttChart();
            ganttChartControl.loadDataIn('GanttDiv', project ? project : Global.project);
            ganttChartControl.AddEventListener("TaskChanged", OnTaskChanged);
            ganttChartControl.AddEventListener("ShowWorkitem", ShowWorkitemList);
            ganttChartControl.AddEventListener("CreateTemplate", CreateTemplate);
            ganttChartControl.AddEventListener("CreateChildTaskWithTemplate", CreateTaskWithTemplate);
        }

        function OnTaskChanged(taskInfo) {
            function AddNewTask(taskInfo) {
                var task = new Task(taskInfo);
                task.ProjectId = Global.projectId;
                task.Id = "00000000-0000-0000-0000-000000000000";
                EzDesk.Service.AddNewTask_Sync(function (e) {
                    var result_task = e.Result;
                    taskInfo.Id = result_task.Id;
                }, { 'projectId': Global.projectId, 'taskStr': $.toJSON(task) });
            }
            function UpdateTask(taskInfo) {
                var task = new Task(taskInfo);
                task.ProjectId = Global.projectId;
                EzDesk.Service.UpdateTask(function (e) {
                    taskInfo.moveChild = false;
                    //dosomething
                }, { 'taskStr': $.toJSON(task), 'moveChild': taskInfo.moveChild });
            }
            function DeleteTask(taskInfo) {
                var task = new Task(taskInfo);
                task.ProjectId = Global.projectId;
                EzDesk.Service.DeleteTask(function (e) {
                    //dosomething
                }, { 'taskId': task.Id });
            }
            var actionMethodMapping = { "Create": AddNewTask, "Delete": DeleteTask, "Change": UpdateTask };
            actionMethodMapping[taskInfo.ClientAction](taskInfo);

        }


        function ShowWorkitemList(taskInfo) {
            currentTaskInfo = taskInfo;
            var convertor = [" ", "内容-计划", "到期", "负责人", "操作"];
            if (taskInfo && taskInfo != null)
                convertor = [" ", "内容", "到期", "负责人", "操作"];

            var args = {
                myConvertor: convertor,
                GetWorkitemListService: getWorkItemListService,
                initCallback: function () {
                    $("#popup-workitemlist-container-1").dialog({
                        height: "auto",
                        width: 600,
                        title: (taskInfo?"计划: " + taskInfo.Name :"项目: " +Global.project.Name) + " 中的任务",
                        modal: true,
                        position: ["center", 200],
                        close: function () { GanttLoad(Global.project); }
                    });
                }
            };

            function getWorkitemsInTask(task, project) {
                if (!task.Workitem) task.Workitem = [];
                var workitems = task.Workitem;
                var subTasks = $.grep(project.Task, function (item, i) { return item.ParentTaskId == task.Id });

                for (var i in subTasks) {
                    var result = (getWorkitemsInTask(subTasks[i], project));
                    workitems = workitems.concat(result);
                }
                return workitems;
            }

            function getWorkItemListService(callback) {
                Global.project = EzDesk.Service.GetFullProjectById_Sync(null, { id: Global.projectId });
                var workitemList = [];
                if (taskInfo && taskInfo != null) {
                    var task = null;
                    for (var q in Global.project.Task) {
                        if (Global.project.Task[q].Id == taskInfo.Id) {
                            task = Global.project.Task[q];
                            break;
                        }
                    }
                    workitemList = getWorkitemsInTask(task, Global.project);
                }
                else
                    workitemList = Global.project.Workitem;

                callback($.grep(workitemList, function (item, index) { return item.IsAvailable }));
            }
            $('#divWorkitems').workitemList(args);
        }

        function CreateTemplate(taskInfo) {
            currentTaskInfo = taskInfo;
            var currentTask = new Task(taskInfo);
            currentTask.ProjectId = Global.projectId;

            $("#create-taskTemplate").dialog({ title: "创建计划模板", width: 600, height: 'auto', position: ["center", 200], modal: true });
            var duration = taskInfo.Duration / 8;

            $("#create-taskTemplate").find('#txt-taskTemplateName').val(taskInfo.Name);
            $("#create-taskTemplate").find('#txt-taskDuration').html(duration);
        }

        function CreateTaskWithTemplate(taskInfo) {
            TaskPanel.init();
            $('#create-taskWithTemplate').dialog({ title: "从模板创建计划", position: ["center", 200] }).dialog('open');
            TaskPanel.onSelected(function (selectedTaskTemplate) {
                $.AjaxBusy.show("创建中...");
                EzDesk.Service.CreateTaskWithTemplate_Sync(function () {
                    GanttLoad(EzDesk.Service.GetFullProjectById_Sync(function () {
                        $.AjaxBusy.hide();
                        $('#create-taskWithTemplate').dialog('close');
                    }, { id: Global.projectId }));
                },
                {
                    'projectId': Global.projectId,
                    'parentTaskId': taskInfo ? taskInfo.Id : null,
                    'taskTemplateId': selectedTaskTemplate.Id
                });
            });
        }

        function doCreateWorkitem() {
            if (WorkitemCreatorSimple) {
                WorkitemCreatorSimple.Show(true, null, Global.project);
                WorkitemCreatorSimple.setTask(currentTaskInfo);
                WorkitemCreatorSimple.SubmitSuccessCallback = function () {
                    ShowWorkitemList(currentTaskInfo);
                };
            }
        };
    </script>
    <script type="text/javascript">
        $(function () {
            function adjustGanttHeight() {
                $('#GanttDiv').height(
                $(window).height()
                - $('#headw').height()
                - ($('#page-head').height() + 10)
                - (22 + 10)
                - ($('#content-foot').height() + 30)
                - 22
                - 60
            );
            }
            $(window).wresize(function () {
                adjustGanttHeight();

                if (Global.project && Global.projectId) {
                    GanttLoad(EzDesk.Service.GetFullProjectById_Sync(undefined, { id: Global.projectId }));
                }
            });

            //初始化修改起始时间功能
            $(".btn-save-word")
            .button({
                icons: {
                    primary: "ui-icon-disk"
                },
                text: true
            });


            $('#btn-change-startOn').click(function () {
                var $panelChangeStartOn = $('#panel-change-startOn')
                $panelChangeStartOn.datepicker({
                    changeMonth: true,
                    numberOfMonths: 2,
                    onSelect: function (dateText, inst) {
                        var startOnDate = $.datepicker.parseDate('yy-mm-dd', dateText).toEpoch();

                        EzDesk.Service.ChangeProjectStartOn_Sync(null, { projectId: Global.projectId, startOn: startOnDate });
                        EzDesk.Service.GetFullProjectById(
                            function (e) {
                                GanttLoad(e);
                            },
                            { id: Global.projectId }
                        );

                        $panelChangeStartOn.hide();
                    }
                });

                $panelChangeStartOn.show();
                $panelChangeStartOn.mouseleave(function () {
                    $panelChangeStartOn.hide();
                });
                var orignalLeft = $('#btn-change-startOn').offset().left;
                $panelChangeStartOn.css({ left: orignalLeft });
            });

            $("#btn-manage-tasktemplate").click(function () {
                TaskPanel.init(true);
                $('#create-taskWithTemplate').dialog({ title: "管理模板", position: ["center", 200] }).dialog('open');
                TaskPanel.onSelected(function (selectedTaskTemplate) {
                    $.AjaxBusy.show("创建中...");
                    EzDesk.Service.CreateTaskWithTemplate_Sync(function () {
                        GanttLoad(EzDesk.Service.GetFullProjectById_Sync(function () {
                            $.AjaxBusy.hide();
                            $('#create-taskWithTemplate').dialog('close');
                        }, { id: Global.projectId }));
                    },
                    {
                        'projectId': Global.projectId,
                        'parentTaskId': taskInfo ? taskInfo.Id : null,
                        'taskTemplateId': selectedTaskTemplate.Id
                    });
                });
            });

            //初始化保存为模板的功能
            $("#btn-ok-createTaskTemplate").click(function () {
                var taskTemplate = {};
                var currentUser = EzDesk.Service.GetCurrentUser_Sync();
                taskTemplate.CreatorId = currentUser.Id;
                taskTemplate.CreatorName = currentUser.Name;
                taskTemplate.Name = $('#txt-taskTemplateName').val();
                taskTemplate.TemplateData = JSON.stringify(currentTaskInfo.GetServerTaskTreeArray());
                var workitems = currentTaskInfo.getWorkitems();
                // 防止循环引用
                for (var index in workitems) {
                    workitems[index].Project = null;
                    workitems[index].Task = null;
                }
                taskTemplate.WorkitemsData = JSON.stringify(workitems);

                taskTemplate.Duration = currentTaskInfo.Duration;
                taskTemplate.Description = $('#txt-taskDescription').val();
                EzDesk.Service.CreateTaskTemplate(function (e) { }, { 'taskTemplateStr': $.toJSON(taskTemplate) });

                //refresh caceh
                EzDesk.Service.GetTaskTemplateList(function () { });
                $("#create-taskTemplate").dialog("close");
            });

            $('#create-taskWithTemplate')
                .dialog({ title: "从模板创建任务", width: 600, height: 'auto', position: ["center", 200], modal: true })
                .dialog('close');
        });
    </script>
</asp:Content>
<asp:Content ID="Content5" ContentPlaceHolderID="PageHead" runat="server">
    <%
        Html.RenderPartial("_sayHello"); %>
</asp:Content>
<asp:Content ID="Content7" ContentPlaceHolderID="PageContent" runat="server">
    <div id="page-head" class="page-head">
        <div id="links">
        </div>
        <% Html.RenderPartial("_projectInfo"); %>
        <div id="tabs">
        </div>
    </div>
    <div id="page-body">
        <div>
            <div>
                <div style="display: block;">
                    <a id="btn-change-startOn"><span class="ui-icon ui-icon-pencil" style="display: inline-block;">
                    </span>变更项目起始时间 </a><a id="btn-manage-tasktemplate"><span class="ui-icon ui-icon-gear"
                        style="display: inline-block;"></span>管理模板 </a>
                    <div id="panel-change-startOn" style="position: absolute; float: left; z-index: 10002;">
                    </div>
                    <div id="create-taskWithTemplate" style="display: none;">
                        <%
                            Html.RenderAction("_taskTemplates");
                        %>
                    </div>
                    <div id="create-taskTemplate" style="display: none;">
                        <ul class="fieldslist">
                            <li>
                                <div class="l">
                                    <label>
                                        模板名称：
                                    </label>
                                </div>
                                <div class="r">
                                    <input class="txtName text" id="txt-taskTemplateName" />
                                    <div id="btn-ok-createTaskTemplate" class="btn-save-word">
                                        保存模板</div>
                                </div>
                            </li>
                            <li>
                                <div class="l">
                                    <label>
                                        计划周期：
                                    </label>
                                </div>
                                <div class="r">
                                    &nbsp;<span id="txt-taskDuration"></span>&nbsp; 天
                                </div>
                            </li>
                            <li>
                                <div class="l">
                                    <label>
                                        备注：
                                    </label>
                                </div>
                                <div class="r">
                                    <textarea id="txt-taskDescription" placeholder="填写一些对于模板的描述" style="min-width: 300px;"></textarea>
                                </div>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
        <div style="width: 100%; min-height: 460px; position: relative" id="GanttDiv">
        </div>
        <div id="log">
        </div>
        <div class="content">
            <div id="popup-workitemlist-container-1" class="content-section" style="display: none;">
                <div id="div-add-workitem" style="float: right;">
                    <div id="btn-add-workitem">
                        添加工作任务</div>
                    <script type="text/javascript">
                        $(function () {
                            $("#btn-add-workitem").button({
                                icons: {
                                    primary: "ui-icon-circle-plus"
                                },
                                text: true
                            });
                        });
                    </script>
                </div>
                <div id="divWorkitems" class="tableContainer">
                </div>
            </div>
        </div>
    </div>
</asp:Content>
<asp:Content ID="Content9" ContentPlaceHolderID="PageFoot" runat="server">
    <div id="tip_Remind" style="display: none;">
        <h1>
            小贴士:</h1>
        <p class="indent">
        </p>
    </div>
    <div>
        <% Html.RenderPartial("_workitemCreatorSimple"); %>
    </div>
</asp:Content>
